/*
 * Created by: Mark Lavrynenko
 * Email:	MarkLavrinenko@gmail.com
 * Project:	  Huffman
*/

#include "FrequencyTable.h"
#include "HuffmanOptions.h"
#include <assert.h>
#ifdef _DEBUG
#include <iostream>
#endif

FrequencyTable::FrequencyTable(void): m_readed(0)
{
	for (size_t i = 0; i < tableSize; ++i)
		table[i] = 0;
}

FrequencyTable::FrequencyTable(uint8_t const* data, size_t len): m_readed(0)
{
	assert(0 == len % tableSize);
	mytype* tmp = (mytype*)data;	
	for (size_t i = 0; i < tableSize; ++i)
	{
		table[i] = tmp[i];
		m_readed += (size_t)table[i];
	}
}

void FrequencyTable::addByte(uint8_t byte)
{
	++m_readed;
	++table[byte];
}

size_t FrequencyTable::totalCount() const
{
	return m_readed;
}

mytype FrequencyTable::countForByte(uint8_t byte)
{
	return table[byte];
}


uint8_t* FrequencyTable::byteRepresentation(size_t& size)
{
	size = headSizeBytes + tableSize * bytesPerSymbol;
	
	// alloc all memory
	uint8_t* ans = new uint8_t[size];
	writeHeader(ans, size - headSizeBytes);

	// why this don't work?????
	//*((size_t*)ans) = size - headSizeBytes;
	
	
	// covert to convenient format
	mytype* arr = (mytype*)(ans + headSizeBytes);
	// write to memory
	for (size_t i = 0; i < tableSize; ++i)
	{
		arr[i] = table[i];
	}

#ifdef _DEBUG
	std::cout << "Frequency table size is " << size  - headSizeBytes << "  + " << headSizeBytes << std::endl;
#endif
	return ans;
}

void FrequencyTable::writeHeader(uint8_t* ans, size_t size)
{
	ans[0] = (size & 0xFF000000) >> 24;
	ans[1] = (size & 0x00FF0000) >> 16;
	ans[2] = (size & 0x0000FF00) >> 8;
	ans[3] = (size & 0x000000FF);
}

